import React from 'react';
import cookies from 'next-cookies';
import Head from 'next/head';

export default class extends React.Component {
  static async getInitialProps(ctx) {
    const i = ctx.query['id'];
    const { token } = cookies(ctx);
    console.log(token);

    let isLogin = true;
    const token_res = await fetch('https://www.tozsy.com/zsy/auth/token', {
      method: 'POST',
      credentials: 'include',
      headers: {
        Cookie: 'token=' + (encodeURIComponent(token) || ''),
      },
    });
    const token_json = await token_res.json();
    if (token_json.state !== 'success') {
      isLogin = false;
    }
    const user = {
      nk: token_json.nk,
      pt: token_json.pt,
      uid: token_json.uid,
      isLogin,
    };

    const zy_res = await fetch('https://www.tozsy.com/zy/homework', {
      method: 'POST',
      credentials: 'include',
      headers: {
        Cookie: 'token=' + (encodeURIComponent(token) || ''),
      },
      body: `{ "id" : ${i} }`,
    });
    const zy_json = await zy_res.json();
    let isExist = true;
    if (zy_json.state !== 'success') {
      isExist = false;
    }
    console.log(zy_json);
    const homework = {
      isExist,
      expiration: zy_json.expiration,
      name: zy_json.name,
      single: zy_json.single,
      id: i,
    };

    let list = {};
    if (user.isLogin === true) {
      const list_res = await fetch('https://www.tozsy.com/zy/list', {
        method: 'POST',
        credentials: 'include',
        headers: {
          Cookie: 'token=' + (encodeURIComponent(token) || ''),
        },
        body: `{ "id" : ${i} }`,
      });
      const list_json = await list_res.json();
      list = {
        isSuccess: list_json.state === 'success',
        error: list_json.error,
        data: list_json.data,
      };
      list.data = list.data.map((item) => {
        item.url = item.url.replace('http://', 'https://');
        return item;
      });
    }

    return {
      user,
      homework,
      log: token_json.state,
      list,
    };
  }

  constructor(props) {
    super(props);
    this.state = {
      user: props.user,
      homework: props.homework,
      log: props.log,
      list: props.list,
    };
  }

  async deleteFile(place) {
    const delete_res = await fetch('https://www.tozsy.com/zy/delete', {
      method: 'POST',
      credentials: 'include',
      // headers: {
      //     'Cookie': 'token=' + (encodeURIComponent(token) || ''),
      // },
      body: `{ "place" : "${place}" }`,
    });
    const delete_json = await delete_res.json();
    if (delete_json.state === 'success') {
      const list = this.state.list;
      list.data = list.data.filter((item) => {
        return item.place !== place;
      });
      this.setState(list);
    } else {
      alert(delete_json.error);
    }
    console.log(delete_json);
  }

  async upload(id) {
    const ele = document.getElementById('upload').files[0];
    if (ele === null) {
      alert('还未选择文件');
      return;
    }
    const name = ele.name;
    if (name === null || name === '') {
      alert('文件名称错误');
      return;
    }

    const pre_res = await fetch('https://www.tozsy.com/zy/preupload', {
      method: 'POST',
      credentials: 'include',
      // headers: {
      //     'Cookie': 'token=' + (encodeURIComponent(token) || ''),
      // },
      body: `{ "id" : ${id}, "name": "${name}" }`,
    });
    const pre_json = await pre_res.json();
    if (pre_json.state === 'error') {
      alert(pre_json.error);
      return;
    }

    pre_json.url = pre_json.url.replace('http://', 'https://');
    // const myHeaders = new Headers();
    // myHeaders.append("Content-Type", "multipart/form-data");
    // myHeaders.append("X-Oss-Callback", pre_json.callback);

    const xhr = new XMLHttpRequest(); //创建对象
    xhr.open('PUT', pre_json.url, true);

    const that = this;
    xhr.onreadystatechange = function () {
      if (xhr.readyState === 4) {
        const obj = JSON.parse(xhr.responseText); //返回值
        console.log(obj);
        if (obj.state !== 'success') {
          alert('上传不成功，可能是因为网络原因。');
        } else {
          e.innerHTML = '';
          that.fetchList();
        }
      }
    };

    xhr.setRequestHeader('Content-Type', 'multipart/form-data');
    xhr.setRequestHeader('X-Oss-Callback', pre_json.callback);
    // const requestOptions = {
    //     method: 'PUT',
    //     headers: myHeaders,
    //     body: ele,
    //     redirect: 'follow'
    // };

    const e = document.getElementById('uploadTip');

    xhr.onprogress = updateProgress;
    xhr.upload.onprogress = updateProgress;
    function updateProgress(event) {
      console.log(event);
      if (event.lengthComputable) {
        const completedPercent = ((event.loaded / event.total) * 100).toFixed(2);
        e.innerHTML = '上传中：' + completedPercent + '%';
      }
    }

    xhr.send(ele);

    // await fetch('https://handle-homework.oss-cn-shenzhen.aliyuncs.com/cors.txt', {
    //     headers: {
    //         "ccc": "ccc",
    //     },
    //     method: "GET",
    // });

    // const up_res = await fetch(pre_json.url, requestOptions);
    // const up_json = await up_res.json();
    // if (up_json.state !== 'success') {
    //     console.log(up_json);
    //     alert('上传不成功，可能是因为网络原因。');
    //     return;
    // }
    // this.fetchList();
  }

  check(stuid) {
    if (stuid === '') {
      alert('学号 不能为空');
      return false;
    } else if (stuid.length !== 12) {
      alert('学号格式错误');
      return false;
    }
    return true;
  }

  toLogin() {
    const stuid = document.getElementById('username').value;
    if (this.check(stuid)) {
      const form = new FormData();
      form.append('stuid', stuid);
      fetch('https://www.tozsy.com/zsy/auth/loginbystuid', {
        method: 'POST',
        body: form,
        credentials: 'include',
      })
        .then((r) => {
          return r.json();
        })
        .then((r) => {
          if (r.state === 'success') {
            this.fetchToken();
            this.fetchList();
          } else {
            alert('校验失败，请再次检查你的输入');
          }
        });
    }
  }

  toLogout() {
    fetch('https://www.tozsy.com/zsy/auth/logout', {
      method: 'POST',
      credentials: 'include',
    })
      .then((r) => r.json())
      .then((r) => {
        if (r.state === 'success') {
          this.setState({
            user: {
              isLogin: false,
            },
          });
        } else {
          alert(r.error);
        }
      });
  }

  async fetchList() {
    const list_res = await fetch('https://www.tozsy.com/zy/list', {
      method: 'POST',
      credentials: 'include',
      body: `{ "id" : ${this.state.homework.id} }`,
    });
    const list_json = await list_res.json();
    const list = {
      isSuccess: list_json.state === 'success',
      error: list_json.error,
      data: list_json.data,
    };
    list.data = list.data.map((item) => {
      item.url = item.url.replace('http://', 'https://');
      return item;
    });
    this.setState({
      list,
    });
  }

  async fetchToken() {
    let isLogin = true;
    const token_res = await fetch('https://www.tozsy.com/zsy/auth/token', {
      method: 'POST',
      credentials: 'include',
    });
    const token_json = await token_res.json();
    if (token_json.state !== 'success') {
      isLogin = false;
    }
    const user = {
      nk: token_json.nk,
      pt: token_json.pt,
      uid: token_json.uid,
      isLogin,
    };
    this.setState({
      user,
    });
  }

  render() {
    console.log('---props---');
    console.log(this.props);
    console.log('---state---');
    console.log(this.state);
    console.log(new Date(this.state.homework.expiration));
    return this.state.homework.isExist === true ? (
      <div>
        <Head>
          <title>{this.state.homework.name}</title>
        </Head>
        <div>
          <div>{this.state.homework.name}</div>
          <div>{`请在 ${new Date(this.state.homework.expiration).getFullYear()} 年 ${
            new Date(this.state.homework.expiration).getMonth() + 1
          } 月 ${new Date(this.props.homework.expiration).getDate()} 日 ${new Date(
            this.props.homework.expiration,
          ).getHours()} 时 ${new Date(this.props.homework.expiration).getMinutes()} 分前提交`}</div>
          {(() => {
            const t = new Date(this.state.homework.expiration) - Date.now();
            if (t <= 0) {
              return <div>作业已截止</div>;
            } else {
              const c = new Date(t);
              console.log(c);
              return <div>作业正在收交中</div>;
            }
          })()}
        </div>
        {this.state.user.isLogin ? (
          <div>
            <div>
              <div>{this.state.user.nk}</div>
              <button onClick={() => this.toLogout()}>登出</button>
            </div>
            {this.state.list.isSuccess ? (
              <div>
                {this.state.list.data.map((item, index) => {
                  return (
                    <div>
                      <div>第 {index + 1} 个文件</div>
                      <div>{item.name}</div>
                      <button onClick={() => this.deleteFile(item.place)}>删除</button>
                      {(() => {
                        const i = item.place.lastIndexOf('.');
                        const suffix = item.place.substring(i + 1).toLowerCase();
                        console.log(suffix);
                        if (suffix === 'png' || suffix === 'jpg' || suffix === 'jpeg') {
                          return (
                            <div>
                              <img src={item.url} />
                            </div>
                          );
                        }
                      })()}
                    </div>
                  );
                })}
                <div>
                  <input id="upload" type="file" accept="image/*" />
                  <button onClick={() => this.upload(this.state.homework.id)}>开始上传</button>
                  <div id="uploadTip"></div>
                  <div>上传成功后将会自动重命名，自动加上水印</div>
                </div>
              </div>
            ) : (
              <div>{this.state.list.error}</div>
            )}
          </div>
        ) : (
          <div>
            <input id="username" placeholder="学号" />
            <button onClick={() => this.toLogin()}>登录</button>
          </div>
        )}
      </div>
    ) : (
      <div>
        <Head>
          <title>作业不存在</title>
        </Head>
        <div>作业不存在</div>
      </div>
    );
  }
}
